package com.shoppingmall.service.impl;

import com.google.common.collect.Lists;
import com.shoppingmall.common.ServletResponse;
import com.shoppingmall.dao.CartMapper;
import com.shoppingmall.dao.ProductMapper;
import com.shoppingmall.pojo.Cart;
import com.shoppingmall.pojo.Product;
import com.shoppingmall.service.CartService;
import com.shoppingmall.utils.BigDecimalUtils;
import com.shoppingmall.vo.CartProductVo;
import com.shoppingmall.vo.CartVo;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by
 *
 * @author touni
 * @date 2019/3/21
 * @time 15:44
 */
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private ProductMapper productMapper;


    @Override
    public ServletResponse getCartList(Integer userId) {

        CartVo cartVo = getAllCartProductByUserId(userId).getData();
        if (null == cartVo){
            return ServletResponse.createByErrorMessage("购物车中没有商品！！！");
        }
        return ServletResponse.createBySuccess(cartVo);
    }

    @Override
    public ServletResponse addOrUpdateProductToCart(Integer userId, Integer productId, Integer count) {
        // 验参  验证product是否存在
        Product productFromQuery = productMapper.selectByPrimaryKey(productId);
        if (null == productFromQuery){
            return ServletResponse.createByErrorMessage("该商品不存在！！！！无法添加");
        }
        //根据userId和ProductId查询是否有cart
        Cart cartListFromUserIdAndProductId = cartMapper.selectByUserIdAndProductId(userId,productId);
        //判断是否有这个，如果没有则表示没有购物车或者购物车没有这个商品，需重新创建
        if (null == cartListFromUserIdAndProductId){
            //用户之前没有购物车或者购物车中没有这个商品，直接插入数据到购物车的表中
            Cart cart = new Cart();
            cart.setChecked(1);//1表示选中
            cart.setProductId(productId);
            cart.setQuantity(count);
            cart.setUserId(userId);
            int flag = cartMapper.insert(cart);
            if (1 != flag){
                return ServletResponse.createByErrorMessage("添加到购物车失败");
            }
            //再次根据userid来查询cartVo
            return getAllCartProductByUserId(userId);
        }
        //如果购物车有这个商品，直接更新数据库
        cartListFromUserIdAndProductId.setQuantity(count);
        int flag = cartMapper.updateByPrimaryKey(cartListFromUserIdAndProductId);
        if (1 != flag){
            return ServletResponse.createByErrorMessage("商品数量更新失败");
        }
        return getAllCartProductByUserId(userId);
    }

    // tip 删除没有核对id是否存在
    @Override
    public ServletResponse deleteProductFromCart(Integer userId,String productIds) {
        String[] idArrays = productIds.split(",");
        for (int i = 0; i < idArrays.length ; i++) {
            int flag = cartMapper.deleteByUserIdAndProductId(userId, Integer.parseInt(idArrays[i]));
            if (1 != flag){
                return ServletResponse.createByErrorMessage("删除失败，请重试");
            }
        }


        return ServletResponse.createBySuccess("删除成功！！！");
    }

    @Override
    public ServletResponse selectOneProduct(Integer userId,Integer productId) {
        //查询
        Cart cart = cartMapper.selectByUserIdAndProductId(userId, productId);
        //修改
        cart.setChecked(1);
        int flag = cartMapper.updateByPrimaryKey(cart);
        if (1 != flag){
        }
        return getAllCartProductByUserId(userId);

    }

    @Override
    public ServletResponse unselectOneProduct(Integer userId, Integer productId) {
        //查询
        Cart cart = cartMapper.selectByUserIdAndProductId(userId, productId);
        //修改
        cart.setChecked(0);
        int flag = cartMapper.updateByPrimaryKey(cart);
        if (1 != flag){
            return ServletResponse.createBySuccessMessage("修改状态失败");
        }
        return getAllCartProductByUserId(userId);

    }

    @Override
    public ServletResponse getCartProductCount(Integer userId) {
        List<Cart> carts = cartMapper.selectByUserId(userId);
        if (CollectionUtils.isEmpty(carts)){
            return ServletResponse.createBySuccess("商品数量为0",0);
        }
        int totalCount = 0;
        for(Cart cart : carts){
            totalCount = totalCount + cart.getQuantity();
        }



        return ServletResponse.createBySuccess(totalCount);
    }

    @Override
    public ServletResponse selectAllProduct(Integer userId) {
        List<Cart> carts = cartMapper.selectByUserId(userId);
        if (CollectionUtils.isEmpty(carts)){
            return ServletResponse.createByErrorMessage("购物车无商品，无法全选");
        }
        for(Cart cart : carts){
            cart.setChecked(1);
            int flag = cartMapper.updateByPrimaryKey(cart);
            if (1 != flag){
                return ServletResponse.createByErrorMessage("全选失败");
            }
        }
        return getAllCartProductByUserId(userId);
    }

    @Override
    public ServletResponse unselectAllProduct(Integer userId) {
        List<Cart> carts = cartMapper.selectByUserId(userId);

        if (CollectionUtils.isEmpty(carts)){
            return ServletResponse.createByErrorMessage("购物车无商品，无法取消全选");
        }
        for(Cart cart : carts){
            cart.setChecked(1);
            int flag = cartMapper.updateByPrimaryKey(cart);
            if (1 != flag){
                return ServletResponse.createByErrorMessage("取消全选失败");
            }
        }
        return getAllCartProductByUserId(userId);
    }


    /**
     * 私有通用的方法
     * 通过userID来查询购物车列表，并封装成一个cartvo  ServletResponse中的data封装的是cartVo
     * @param userId
     * @return
     */
    private ServletResponse<CartVo> getAllCartProductByUserId(Integer userId){

        //一个用户可能有多个购物车
        List<Cart> cartListFromQuery =cartMapper.selectByUserId(userId);
        if (CollectionUtils.isEmpty(cartListFromQuery)){
            //查询结果为空 表明没有购车
            return ServletResponse.createBySuccessMessage("购物车中没有商品");
        }
        //遍历集合，查询所有的商品，封装cartProductVoList  封装的时候顺便计算总价
        BigDecimal totalPrice = new BigDecimal("0");

        List<CartProductVo> cartProductVoList  = Lists.newArrayList();
        for(Cart cart:cartListFromQuery){
            //获取到prodcutid查询商品的详情 封装cartProductVo
            CartProductVo cartProductVo = new CartProductVo();
            Product productFromQuery = productMapper.selectByPrimaryKey(cart.getProductId());
            cartProductVo.setId(cart.getId());
            cartProductVo.setUserId(userId);
            cartProductVo.setProductId(cart.getProductId());
            cartProductVo.setQuantity(cart.getQuantity());  //指的是购物车中的数量
            cartProductVo.setProductName(productFromQuery.getName());
            cartProductVo.setProductSubtitle(productFromQuery.getSubtitle());
            cartProductVo.setProductMainImage(productFromQuery.getMainImage());
            cartProductVo.setProductPrice(productFromQuery.getPrice());
            cartProductVo.setProductStatus(productFromQuery.getStatus());
            BigDecimal simpleProductTotalPrice = BigDecimalUtils.multiplyData(cart.getQuantity().toString(),productFromQuery.getPrice().toString());// 计算单一商品的总价
            //增加逻辑 如果商品被选中就计入总价
            if (cart.getChecked()== 1) {
                totalPrice = totalPrice.add(simpleProductTotalPrice);
            }
            cartProductVo.setProductTotalPrice(simpleProductTotalPrice);
            cartProductVo.setProductStock(productFromQuery.getStock());
            cartProductVo.setProductChecked(cart.getChecked());
            //设置limitQuantity属性  只判断单一用户购物车内数量与数据库中数量相比
            if (cart.getQuantity() <= productFromQuery.getStock()){
                //库存充足
                cartProductVo.setLimitQuantity("true");

            }
            cartProductVoList.add(cartProductVo);
        }
        //开始封装 cartVo
        CartVo cartVo = new CartVo();
        cartVo.setCartProductVoList(cartProductVoList);
        cartVo.setAllChecked(cartMapper.selectStatusByUserId(userId) == 0?true:false);  //用户id查询是否有未选择的商品，如果有则返回数据
        cartVo.setCartTotalPrice(totalPrice);
        //todo imageHost这个属性暂时没有封装进去

        return ServletResponse.createBySuccess(cartVo);


    }







}
